package com.lq.email.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lq.email.entity.UserEmail;
import com.lq.email.exception.MyException;
import com.lq.email.mapper.UserEmailMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * @ClassName MyJavaMailSender
 * @Description
 * @Author LQ
 * @Date 2021/10/5 18:42
 * @Version 1.0
 */
@Component
public class MyJavaMailSender {

    @Autowired
    private UserEmailMapper userEmailMapper;

    public JavaMailSenderImpl getJavaMailSender(String userId) throws MyException {
        if (StringUtils.isBlank(userId)) {
            throw new MyException("用户id不能为空");
        }
        QueryWrapper<UserEmail> warpper = new QueryWrapper<>();
        warpper.eq("userid", userId);
        UserEmail userEmail = userEmailMapper.selectOne(warpper);
        return getJavaMailSender(userEmail);
    }

    public JavaMailSenderImpl getJavaMailSender(UserEmail userEmail) throws MyException {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(StringUtils.isNotBlank(userEmail.getHost()) ? userEmail.getHost() : "smtp.qq.com");
        if (StringUtils.isBlank(userEmail.getEmaileSendForm())) {
            throw new MyException("发送邮箱不能为空");
        }
        //发送邮件的账号
        javaMailSender.setUsername(userEmail.getEmaileSendForm());
        if (StringUtils.isBlank(userEmail.getEmailPassword())) {
            throw new MyException("邮箱授权码不能为空");
        }
        //授权码
        javaMailSender.setPassword(userEmail.getEmailPassword());
        javaMailSender.setDefaultEncoding(StringUtils.isNotBlank(userEmail.getEncoding()) ? userEmail.getEncoding() : "UTF-8");

        Properties properties = new Properties();
        //properties.setProperty("mail.debug", "true");//启用调试
        //properties.setProperty("mail.smtp.timeout", "1000");//设置链接超时
        //设置通过ssl协议使用465端口发送、使用默认端口（25）时下面三行不需要
        properties.setProperty("mail.smtp.socketFactory.class", StringUtils.isNotBlank(userEmail.getSocketFactoryClass()) ? userEmail.getSocketFactoryClass() : "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.socketFactory.port", (userEmail.getPort() != null) ? String.valueOf(userEmail.getPort()) : "465");
        //开启认证
        properties.setProperty("mail.smtp.auth", "true");
        //设置ssl端口
        javaMailSender.setJavaMailProperties(properties);
        return javaMailSender;
    }
}
